package com.zdy.showgoods;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Intent;
import android.support.annotation.MainThread;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.networklibrary.BaseObserver;
import com.example.networklibrary.MD5;
import com.example.networklibrary.RxHttp;
import com.example.networklibrary.SharedPreferencesUtils;
import com.example.networklibrary.ToastUtils;
import com.example.networklibrary.config.KeyInterface;
import com.example.networklibrary.entity.RequestEntity;
import com.example.networklibrary.model.ProductListModel;
import com.example.networklibrary.model.ProductRecordModel;
import com.example.networklibrary.model.RFID;
import com.example.networklibrary.model.RecommendModel;
import com.example.networklibrary.model.UserInfo;
import com.zdy.adapter.MyAdapter;
import com.zdy.adapter.ProductListAdapter;
import com.zdy.itemdecoration.SpaceItemDecoration;
import com.zdy.modellibrary.base.BaseActivity;
import com.zdy.widget.HorizontalListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class ActivityProduct extends BaseActivity implements View.OnClickListener {
    private ImageView product_back;
    private RecyclerView product_list;
    private List<ProductListModel> productListModelList = new ArrayList<>();
    private CopyOnWriteArrayList<String> codeList = new CopyOnWriteArrayList<>();//rfidList
    private ProductListAdapter productListAdapter;
    private FragmentPagerAdapter fragmentStatePagerAdapter;
    private LinearLayout indicatior;
    private LinkedHashMap<String, String> secureMap = new LinkedHashMap<>();
    private Map<Integer, Integer> skuBindFragment = new HashMap<>();
    private String[] tags = new String[5];
    private int index = 0;
    private ViewPager viewPager;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String code = intent.getExtras().getString("Code");
        if (!secureMap.containsValue(code)) {
            secureMap.put(code, code);
            codeList.add(code);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product);
        String code = getIntent().getExtras().getString("Code");
        secureMap.put(code, code);
        codeList.add(code);
        //员工码加入
        String staffInfo = SharedPreferencesUtils.getString(this, KeyInterface.StaffInfo);
        UserInfo userInfo = JSONObject.parseObject(staffInfo, UserInfo.class);
        secureMap.put(userInfo.getStaff_number(), userInfo.getStaff_number());
        initView();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private void initView() {
        product_back = findViewById(R.id.product_back);
        product_list = findViewById(R.id.product_list);
        product_back.setOnClickListener(this);
        indicatior = findViewById(R.id.product_indicator);
        initViewPater();
        initRecyclerView();
    }

    private void initViewPater() {
        viewPager = findViewById(R.id.product_viewpager);
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentStatePagerAdapter = new FragmentPagerAdapter(fragmentManager) {
            @Override
            public Fragment getItem(int position) {
                ProductFragment productFragment = new ProductFragment();
                Bundle bundle = new Bundle();
                bundle.putString("Code", codeList.get(position));
                productFragment.setArguments(bundle);
                productFragment.setItemClickListener(new ProductFragment.ItemClickListener() {
                    @Override
                    public void toInfo(ProductListModel item) {
                        toInfoActivity(item);
                    }
                });
                return productFragment;
            }

            @Override
            public int getCount() {
                return codeList.size();
            }

            @Override
            public int getItemPosition(Object object) {
                return super.getItemPosition(object);
            }

            @Override

            public Object instantiateItem(ViewGroup container, int position) {
                return super.instantiateItem(container, position);

            }


            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                super.destroyItem(container, position, object);
            }
        };
        viewPager.setAdapter(fragmentStatePagerAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (!skuBindFragment.containsKey(position)) return;
                RecommendModel recommendModel = new RecommendModel();
                recommendModel.setSku_id(skuBindFragment.get(position));
                loadProductRecommand(recommendModel);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        initIndicator();
    }

    private void initIndicator() {
        indicatior.removeAllViews();
        for (int i = 0; i < codeList.size(); i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.item_indicator, null);
            TextView textView = view.findViewById(R.id.item_indicator_tv);
            textView.setText((i + 1) + "");
            indicatior.addView(textView);
        }
    }

    private void initRecyclerView() {
        LinearLayoutManager gridLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        product_list.setLayoutManager(gridLayoutManager);
        product_list.setAdapter(productListAdapter = new ProductListAdapter(this, productListModelList, this));
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.product_back) {
            finish();
        }
    }

    @Subscribe
    public void receiveTag(RFID rfid) {
        if (isTopActivity()) {
            if (secureMap.containsKey(rfid.getCode()) && !single(rfid.getCode())) return;
            if (secureMap.containsValue(rfid.getCode())) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        int i = codeList.indexOf(rfid.getCode());
                        viewPager.setCurrentItem(i, true);
                    }
                });
                return;
            }
            secureMap.put(rfid.getCode(), rfid.getCode());
            codeList.add(rfid.getCode());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    fragmentStatePagerAdapter.notifyDataSetChanged();
                    initIndicator();
                }
            });
        }
    }

    //判断是否含有多个(避免viewpager 跳动)
    private synchronized boolean single(String tag) {
        tags[index] = tag;
        index++;
        if (index >= tags.length) {
            index = 0;
        }
        for (int i = 0; i < tags.length - 1; i++) {
            if (!tags[i].equals(tags[i + 1])) {
                return false;
            }
        }
        return true;
    }

    public void toInfoActivity(ProductListModel item) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("Item", item);
        turnToNextActivity(ActivityGoodsInfo.class, bundle);
    }

    private boolean isTopActivity() {
        boolean isTop = false;
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        if (cn.getClassName().contains("ActivityProduct")) {
            isTop = true;
        }
        return isTop;
    }

    @Subscribe
    public void loadProductRecommand(RecommendModel recommendModel) {
        if (!skuBindFragment.containsKey(viewPager.getCurrentItem())) {
            skuBindFragment.put(viewPager.getCurrentItem(), recommendModel.getSku_id());
        }
        RequestEntity requestEntity = new RequestEntity();
        JSONObject body = new JSONObject();
        body.put("sku_id", recommendModel.getSku_id());
        requestEntity.setBody(body);
        JSONObject header = new JSONObject();
        header.put("request_seq", KeyInterface.REQUEST_SEQ);
        header.put("sign", "");
        header.put("curr_page", 1);
        header.put("page_size", 50);
        header.put("sys_id", KeyInterface.SYS_ID);
        header.put("tra_code", KeyInterface.RECOMMANDPRODUCT);
        requestEntity.setHeader(header);
        try {
            String signString = JSONObject.toJSONString(requestEntity);
            String sign = MD5.getSign(signString);
            header.put("sign", sign);
            requestEntity.setHeader(header);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String json = "";
        try {
            json = URLEncoder.encode(JSONObject.toJSONString(requestEntity), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        RxHttp.getInstance()
                .getSyncServer()
                .parseArray(SharedPreferencesUtils.getString(this, KeyInterface.AppURL), json)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<JSONArray>() {
                    @Override
                    public void onSuccess(JSONArray result) {
                        try {
                            productListModelList.clear();
                            productListModelList.addAll(JSONArray.parseArray(result.toJSONString(), ProductListModel.class));
                            productListAdapter.notifyDataSetChanged();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Throwable e, String errorMsg) {
                        ToastUtils.showShort("获取推荐错误");
                    }
                });
    }
}
